<?php

class ProductController extends CController
{

	/**
	 * @var string specifies the default action to be 'list'.
	 */
	public $defaultAction='list';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			array('application.filters.LoginFilter +create,update,delete'),
		);
	}
	
	/**
	 * Shows a particular model.
	 */
	public function actionShow()//用户后台查看
	{
		$this->render('show',array('model'=>$this->loadProduct()));
	}
	
	public function actionGet_product(){
		$criteria=new CDbCriteria();
		$criteria->select='product.*,areas.name as area_name,city.name as city_name,
		province.name as province_name,business.name as business_name,business.linkman_tel as business_tel,
		business.linkman as business_linkman,business.brand as business_brand';
		$criteria->join='INNER JOIN business ON business.id=product.fk_business_id
						 INNER JOIN areas ON business.area=areas.code
						 INNER JOIN areas as city ON left(business.area,4)=city.code
						 INNER JOIN areas as province ON left(business.area,2)=province.code';
		$criteria->addCondition('product.id='.$_GET['id']);
		$model=Product::model()->find($criteria);
		$this->pageTitle=Yii::app()->name.'-'.$model->name;
		
		$criteria=new CDbCriteria();//读取产品厂家其他产品
		$criteria->select='id,name,logo';
		$criteria->addCondition('fk_business_id='.$model->fk_business_id);
		$criteria->limit=5;
		$products=Product::model()->findAll($criteria);
		
		$sort_models=array();
		if(isset($_POST['product_sort']))$_GET['product_sort']=$_POST['product_sort'];
		if(isset($_GET['product_sort'])){ 
			$product_sort=$_GET['product_sort'];
			$sql="select code,name from business_sorts where code='".substr($product_sort,0,2)."' or code='$product_sort' order by code";
			$sort_models=array('sort_name'=>Business_sorts::model()->findAllBySql($sql));
			$sql="select id,name from business where id=".$model->fk_business_id;
			$sort_models['business']=Business::model()->findBySql($sql);
		}
		$this->render('get_product',array('model'=>$model,'products'=>$products)+$sort_models);
	}	

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionCreate()
	{
		/*//判断是否有存在系列
		$sql="select * from product_series where state=0 and fk_business_id=".Yii::app()->session['business_id'];
		$series_models=Product_series::model()->findAllBySql($sql);
		if(empty($series_models))
			$this->redirect(array('product_series/create','mess'=>'请添加产品系列后添加产品.'));
		*/	
		Yii::app()->session['upload_product_times']=0;
		Yii::app()->session['upload_product_logo_times']=0;
		
		$model=new Product;
		if(isset($_POST['Product']))
		{
			$model->attributes=$_POST['Product'];
			if($model->save())
				$this->redirect(array('show','id'=>$model->id));
		}
		/*
		foreach($series_models as $val){
			$series[$val->id]=$val->name;
		}
		*/
		$this->render('create',array('model'=>$model));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionUpdate()
	{
		Yii::app()->session['upload_product_times']=0;
		Yii::app()->session['upload_product_logo_times']=0;
		$model=$this->loadProduct();
		if(isset($_POST['Product']))
		{
			$model->attributes=$_POST['Product'];
			if($model->save())
				$this->redirect(array('show','id'=>$model->id)+$_GET);
		}
		/*//产品系列
		$sql="select * from product_series where state=0 and fk_business_id=".Yii::app()->session['business_id'];
		$series_models=Product_series::model()->findAllBySql($sql);
		foreach($series_models as $val){
			$series[$val->id]=$val->name;
		}*/
		$this->render('update',array('model'=>$model));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'list' page.
	 */
	public function actionDelete()
	{
		if(isset($_GET['id'])){
			Product::model()->updateByPk($_GET['id'],array('state'=>1),array('fk_business_id'=>Yii::app()->session['business_id']));
			unset($_GET['id']);
			$this->redirect(array('admin')+$_GET);
		}
		else
			throw new CHttpException(400,'无法获得要删除的信息ID!');
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=Product::model();
		$criteria=new CDbCriteria;
		///$criteria->join='INNER JOIN product_series ON product_series.id=fk_series_id';
		//$criteria->select='product.*,product_series.name as series';
		$criteria->addCondition('product.state<>1 and product.fk_business_id='.Yii::app()->session['business_id']);
		
		$pages=new CPagination(Product::model()->count($criteria));
		$pages->pageSize=Yii::app()->params['page_size']['user_product'];
		$pages->applyLimit($criteria);

		$sort=new CSort('Product');
		//$sort->attributes=array_merge($model->attributeNames(),array('series'));
		$sort->applyOrder($criteria);

		$models=$model->findAll($criteria);

		$this->render('admin',array(
			'models'=>$models,
			'pages'=>$pages,
			'sort'=>$sort,
		));
	}
	
	public function actionUploadedFiles()
	{
		$state=$this->uploadfile('filedata');
		echo json_encode($state);
	}
	
	function uploadfile($inputname)
	{
		$mode=isset($_GET['mode'])?$_GET['mode']:'product';
		$mode_times="upload_{$mode}_times";
		
		$times=isset(Yii::app()->session[$mode_times])?Yii::app()->session[$mode_times]:0;
		if($times>=Yii::app()->params[$mode_times])
			return array('err'=>'一次性最多上传'.Yii::app()->params[$mode_times].'次图片,如仍需继续上传请提交信息后修改信息,或刷新本页进行上传.','msg'=>'');
		Yii::app()->session[$mode_times]=++$times;
			
		$immediate=isset($_GET['immediate'])?$_GET['immediate']:0;
		$attachdir='upload/temp/'.$mode;//上传文件保存路径，结尾不要带/
		$dirtype=1;//1:按天存入目录 2:按月存入目录 3:按扩展名存目录  建议使用按天存
		$maxattachsize=Yii::app()->params["upload_{$mode}_size"][0];//最大上传大小
		$maxsizemsg=Yii::app()->params["upload_{$mode}_size"][1];
		$upext='txt,rar,zip,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid';//上传扩展名
		$msgtype=2;//返回上传参数的格式：1，只返回url，2，返回参数数组
	
		$err = "";
		$msg = "";
		if(!isset($_FILES[$inputname]))return array('err'=>'文件域的name错误或者没选择文件','msg'=>$msg);
		$upfile=$_FILES[$inputname];
		if(!empty($upfile['error']))
		{
			switch($upfile['error'])
			{
				case '1':
					$err = '文件大小超过了php.ini定义的upload_max_filesize值';
					break;
				case '2':
					$err = '文件大小超过了HTML定义的MAX_FILE_SIZE值';
					break;
				case '3':
					$err = '文件上传不完全';
					break;
				case '4':
					$err = '无文件上传';
					break;
				case '6':
					$err = '缺少临时文件夹';
					break;
				case '7':
					$err = '写文件失败';
					break;
				case '8':
					$err = '上传被其它扩展中断';
					break;
				case '999':
				default:
					$err = '无有效错误代码';
			}
		}
		elseif(empty($upfile['tmp_name']) || $upfile['tmp_name'] == 'none')$err = '无文件上传';
		else
		{
			$temppath=$upfile['tmp_name'];
			$fileinfo=pathinfo($upfile['name']);
			$extension=$fileinfo['extension'];
			if(preg_match('/'.str_replace(',','|',$upext).'/i',$extension))
			{
				$filesize=filesize($temppath);
				if($filesize > $maxattachsize)$err='文件大小超过'.$maxsizemsg.'字节';
				else
				{
					switch($dirtype)
					{
						case 1: $attach_subdir = date('Y').'/'.date('m').'/'.date('d'); break;
						case 2: $attach_subdir = 'month_'.date('ym'); break;
						case 3: $attach_subdir = 'ext_'.$extension; break;
					}
					$attach_dir = $attachdir.'/'.$attach_subdir;
					if(!is_dir($attach_dir))
					{
						@mkdir($attach_dir, 0777,true);
						@fclose(fopen($attach_dir.'/index.htm', 'w'));
					}
				PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
				$filename=date("YmdHis").mt_rand(1000,9999).'.'.$extension;
				$target = $attach_dir.'/'.$filename;
				
				move_uploaded_file($upfile['tmp_name'],$target);
				if($immediate=='1')$target='!'.$target;
				if($msgtype==1)$msg=$target;
				else $msg=array('url'=>$target,'localname'=>$upfile['name'],'id'=>'1');//id参数固定不变，仅供演示，实际项目中可以是数据库ID
			}
		}
		else $err='上传文件扩展名必需为：'.$upext;

		@unlink($temppath);
	}
	return array('err'=>$err,'msg'=>$msg);
	}
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
	 */
	public function loadProduct($id=null)
	{
		if($this->_model===null)
		{
			$criteria=new CDbCriteria();
			//$criteria->select='product.*,product_series.name as series';
			//$criteria->join='INNER JOIN product_series ON product_series.id=product.fk_series_id';
			$criteria->addCondition('product.id='.(isset($_GET['id'])?$_GET['id']:$id).' and product.fk_business_id='.Yii::app()->session['business_id']);
			$this->_model=Product::model()->find($criteria);
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}
	
	public function actionTest(){
		$image = Yii::app()->image->load('images/01.jpg');
		$image->resize(400, 100)->rotate(-45)->quality(75)->sharpen(20);
		$image->render();
	}
}
